package com.feilong.edgeAI.utils;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;

import androidx.annotation.RequiresApi;

public class FlashlightManager {

    private static CameraManager cameraManager;
    private static String cameraId;

    public static void init(Context context) {
        cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        try {
            cameraId = cameraManager.getCameraIdList()[0]; // 获取第一个相机的ID
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void turnOn() {
        try {
            cameraManager.setTorchMode(cameraId, true); // 打开闪光灯
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void turnOff() {
        try {
            cameraManager.setTorchMode(cameraId, false); // 关闭闪光灯
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    public static boolean isFlashlightOn() {
        Camera camera = Camera.open();
        if (camera == null) {
            return false;
        }
        Camera.Parameters params = camera.getParameters();
        String flashMode = params.getFlashMode();
        if (flashMode == null) {
            return false;
        }
        boolean isFlashOn = flashMode.equals(Camera.Parameters.FLASH_MODE_TORCH);
        camera.release();
        return isFlashOn;
    }
}
